package com.shuai.service.impl;


;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shuai.constant.MessageConstant;
import com.shuai.context.BaseContext;
import com.shuai.dto.PasswordEditDTO;
import com.shuai.dto.UserDTO;
import com.shuai.dto.UserLoginDTO;
import com.shuai.dto.UserPageQueryDTO;
import com.shuai.entity.User;
import com.shuai.exception.AccountNotFoundException;
import com.shuai.exception.PasswordErrorException;
import com.shuai.mapper.ProjectUserRelationMapper;
import com.shuai.result.PageResult;
import com.shuai.service.UserService;
import com.shuai.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.shuai.mapper.UserMapper;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProjectUserRelationMapper projectUserRelationMapper;

    @Autowired
    private BaseContentService baseContentService;

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对密码进行md5加密改造
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 新增员工
     * @param userDTO
     */
    @Override
    public void save(UserDTO userDTO) {
        User user = new User();

        //对象属性拷贝
        BeanUtils.copyProperties(userDTO,user);

        //密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        //设置默认昵称
        user.setName(user.getUsername());


        //设置当前记录的创建时间和修改时间
        //user.setUpdateTime(LocalDateTime.now());
        //user.setCreateTime(LocalDateTime.now());

        //设置

        //调用持久层插入员工数据
        userMapper.insert(user);
    }

    /**
     * 分页查询员工信息
     * @param userPageQueryDTO
     *@return PageResult
     * */
    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        //分页查询
        PageHelper.startPage(userPageQueryDTO.getPage(),userPageQueryDTO.getPageSize());

        //设置企业id
        userPageQueryDTO.setEnterpriseId(baseContentService.getEnterpriseId());

        Page<UserVO> page = userMapper.pageQuery(userPageQueryDTO);

        Long total = page.getTotal();
        List<UserVO> records = page.getResult();

        return new PageResult(total, records);
    }


    /**
     *根据id查询员工信息
     * */
    @Override
    public User getById(Long id) {
        User user = userMapper.getById(id);
        user.setPassword("****");
        return user;
    }

    /**
     * 修改员工信息
     * @param userDTO
     * */
    @Override
    public void update(UserDTO userDTO) {
        //将DTO转换为实体对象,属性拷贝
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);

        //user.setUpdateTime(LocalDateTime.now());
        //user.setUpdateUser(BaseContext.getCurrentId());

        userMapper.update(user);
    }

    /**
     * 修改密码
     * */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {

        //检查旧密码
        int result = userMapper.checkPassword(passwordEditDTO.getId(), DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes(StandardCharsets.UTF_8)));
        if (result == 0) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //更新密码
        userMapper.updatePassword(passwordEditDTO.getId(), DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes(StandardCharsets.UTF_8)));
    }

    @Override
    public void invite(Long id) {
        //1、根据用户名查询数据库中的数据

        User user = userMapper.getById(id);
        if (user == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //TODO 实现消息推送发送邀请信息

        Long enterpriseId = baseContentService.getEnterpriseId();
        user.setEnterpriseId(enterpriseId);

        userMapper.update(user);
    }

    @Override
    public List<UserVO> listAllUsersInEnterprise() {
        Long enterpriseId = baseContentService.getEnterpriseId();
        List<UserVO> users = userMapper.listAllUsersInEnterprise(enterpriseId);
        return users;
    }


    /**
     * 将员工移出企业同时删除关联关系
     * @param id
     */
    @Override
    @Transactional
    public void deleteInEnterpriseWithProjectRelation(Long id) {
        User user = userMapper.getById(id);
        user.setEnterpriseId(Long.valueOf(0));
        user.setPermission(Integer.valueOf(0));
        userMapper.update(user);
        Long userId = user.getId();
        projectUserRelationMapper.deleteByProjectUserId(userId);
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    @Override
    public List<UserVO> listByUsername(String username) {
        //排除已经在企业中的用户
        Long enterpriseId = baseContentService.getEnterpriseId();
        return userMapper.listByUsername(username,enterpriseId);
    }

    @Override
    public void modifyAvatar(String avatarUrl) {
        User user = new User();
        user.setAvatar(avatarUrl);
        user.setId(BaseContext.getCurrentLoginInfo().getId());
        userMapper.update(user);
    }


}
